<?php
/**
 * Created by PhpStorm.
 * User: guokunsheng
 * Date: 2018/6/6
 * Time: 17:38
 */

namespace app\common\model;

use think\Cache;

class MapCollect extends Base
{
    protected $table = 'wechat_backup_07_18_14_43_00.app_map_collect';

    /**
     * 收藏详情 redis key
     */
    const REDIS_KEY_MAP_COLLECT_DETAIL = 'map_collect_list_detail1_';
    const MAP_COLLECT_RIDS = 'map_collect_rids1_';
    const MAP_COLLECT_LIST_IDS = 'map_collect_list_ids1_';
    const MAP_COLLECT_LIST = 'map_collect_list1_';

    public function map()
    {
        return $this->hasOne('Map', 'id', 'mid', 'm');
    }

    /**
     * 获取收藏数据-- 根据rid
     * @param array $map
     * @return array|bool|mixed|string
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function collect_rid($map = [])
    {
        $uid = $map['uid'];

        $is_use_cache = 1;
        if ($is_use_cache)
        {

            //获取 用户所有收藏幸运之城地点的rids
            $map_collect_rids = false;
            if ($this->cache_on >= 1)
            {
                $map_collect_rids = Cache::get(self::MAP_COLLECT_RIDS . $map['uid']);
            }
            if ($map_collect_rids === false)
            {
                $c_rid = $this
                    ->alias('co')
                    ->field('co.rid')
                    ->join('wechat_backup_07_18_14_43_00.app_recode r', 'r.id = co.rid', 'LEFT')
                    ->where(['co.uid' => $uid,'r.status'=>1])
                    ->order('co.id ASC')
                    ->distinct('co.rid')
                    ->select();
                //获取数据
                $c_rid = json_decode(json_encode($c_rid, true), true);

                //存储所有rids
                foreach ($c_rid as $k => $v)
                {
                    $map_collect_rids .= ',' . $v['rid'];
                }

                if ($this->cache_on >= 1)
                    Cache::set(self::MAP_COLLECT_RIDS . $map['uid'], $map_collect_rids, $this->cache_time);
            }

            $map_collect_rids = explode(',', $map_collect_rids);//将 $map_collect_rids 转换为数组
            array_shift($map_collect_rids);//去除数组第一个元素
            if (count($map_collect_rids) == 0)
            {//如果rids为空，那么直接返回
                $result = [
                    'total' => 0,
                    'per_page' => 10,
                    'current_page' => 1,
                    'last_page' => 0,
                    'rids' => [],
                    'data' => []
                ];
                return $result;
            }
            if (!in_array($map['rid'], $map_collect_rids))
            {//如果用户传过来的rid不在列表中，就是用第一个rid
                $map['rid'] = $map_collect_rids[0];
            } else
            {
                if ($map['is_self'] === 1 && $offset = array_search($map['rid'], $map_collect_rids))
                {//如果在列表里，并且不在第一个位置，那么 把这个用户的id移到第一个位置（解决ios bug）
                    unset($map_collect_rids[$offset]);
                    array_unshift($map_collect_rids, $map['rid']);
                }
            }

            //获取当前档案下的所有收藏地点的id，同时更新缓存
            $result = false;
            $where = ['rid' => $map['rid'], 'uid' => $map['uid']];
            if ($this->cache_on >= 1)
            {
                $result = Cache::get(self::MAP_COLLECT_LIST_IDS . $map['rid']);
            }
            if ($result === false)
            {
                try
                {
                    //获取所有的收藏id
                    $data = $this
                        ->alias('mc')
                        ->field('mc.id')
                        ->join('wechat_backup_07_18_14_43_00.app_map m', 'mc.mid=m.id', 'INNER')
                        ->where($where)
                        ->order('id DESC')
                        ->select();
                }
                catch (\Exception $e)
                {
                    $result = [
                        'rids' => $map_collect_rids,
                        'data' => []
                    ];

                }
                $ids = json_decode(json_encode($data, true), true);
                //存储当前档案下的所有收藏地点的id
                foreach ($ids as $k => $v)
                {
                    $result .= ',' . $v['id'];
                }

                if ($this->cache_on >= 1)
                {//把当前档案下的，所有收藏地点的id，存到redis中
                    Cache::set(self::MAP_COLLECT_LIST_IDS . $map['rid'], $result, $this->cache_time);
                }
            }

            //进行分页返回数据
            $ids = explode(',', $result);
            array_shift($ids);//去除数组第一个元素
            $total = count($ids);//统计有多少个id
            $data_list = getPaginatorData($total, $map['page'], 10);//获取数据分页信息
            $result = array_slice($ids, $data_list['start'], 10);//获取分页后的id数组
            unset($data_list['start']);
            unset($data_list['end']);

            //组装所有的ids
            $map_collect_ids = [];
            foreach ($result as $mid)
            {//根据id，循环获取详情内容
                $map_collect_ids[]['id'] = $mid;
            }
            $data_list['data'] = $this->getMapDetails($map_collect_ids, ['rid' => $map['rid'], 'uid' => $map['uid']]);
            $data_list['rids'] = $map_collect_rids;

            return $data_list;
        } else
        {
            $c_rid = $this->field('rid')->where('uid', $map['uid'])->order('id ASC')->distinct('rid')->select();
            $c_rid = json_decode(json_encode($c_rid, true), true);
            $rids = [];

            foreach ($c_rid as $k => $v)
            {
                $rids[] = $v['rid'];
            }

            if(empty($rids)){
                return [
                    'rids' => [],
                    'data' => []
                ];
            }

            if (empty($map['rid'])) {
                do{
                    $map['rid'] = $rids[0];

                    $recode = (new Recode())->getRecode(['id' => $map['rid']]);
                    if (!$recode || $recode['status'] != 1)
                    {
                        unset($rids[0]);
                        $map['rid'] = 0;
                    }
                }while($rids && $map['rid'] === 0);
            }

            $where = ['rid' => $map['rid'], 'uid' => $map['uid']];

            $result = false;
            if ($this->cache_on >= 1)
            {
                Cache::get(self::MAP_COLLECT_LIST . $map['rid']);
            }
            if ($result === false)
            {
                try
                {
                    $result = $this
                        ->alias('mc')
                        ->field('mc.type,mc.id,mc.name,mc.des,m.longitude,m.latitude')
                        ->join('wechat_backup_07_18_14_43_00.app_map m', 'mc.mid=m.id', 'INNER')
                        ->where($where)
                        ->order('id DESC')
                        ->paginate(10, false, ['page' => $map['page']]);

                }
                catch (\Exception $e)
                {
                    $result = [
                        'rids' => $rids,
                        'data' => []
                    ];

                }
                $result = json_decode(json_encode($result, true), true);

                if ($this->cache_on >= 1)
                    Cache::set(self::MAP_COLLECT_LIST . $map['rid'], $result, $this->cache_time);
            }

            $result['rids'] = $rids;

            return $result;
        }

    }

    /**
     * 获取单个地点收藏的详情（如果不存在那么查库，放入缓存，如果存在，直接从缓存里取）
     * @param array $all_list
     * @param $map
     * @return array|false|mixed|\PDOStatement|string|\think\Model
     */
    public function getMapDetails($all_list = [], $map)
    {
        $result = [];
        $ids = $this->getAllNotCachedIds($all_list, self::REDIS_KEY_MAP_COLLECT_DETAIL);
        try
        {
            if (strlen($ids) > 0)
            {
                $where = 'mc.id in(' . $ids . ') and rid=' . (int)($map['rid']) . ' and uid=' . (int)($map['uid']);
                //获取所有的收藏id
                $result = $this
                    ->alias('mc')
                    ->field('mc.id,mc.type,mc.id,mc.name,mc.des,m.longitude,m.latitude')
                    ->join('wechat_backup_07_18_14_43_00.app_map m', 'mc.mid=m.id', 'INNER')
                    ->where($where)
                    ->order('mc.id DESC')
                    ->select();
                $result = json_decode(json_encode($result, true), true);
                if ($this->cache_on >= 1)
                    foreach ($result as $v)
                        Cache::set(self::REDIS_KEY_MAP_COLLECT_DETAIL . $v['id'], $v, $this->cache_time);
            }
            if ($this->cache_on >= 1)//如果缓存打开，循环获取，因为缓存里已经有了数据
            {
                $result = [];
                foreach ($all_list as $v)
                    $result[] = Cache::get(self::REDIS_KEY_MAP_COLLECT_DETAIL . $v['id']);
            }
        }
        catch (\Exception $e)
        {
            // 错误信息写入日志
            \think\Log::write('获取用户收藏幸运之城详情错误:' . '[' . $map['rid'] . ']', 'error', true);
        }

        return $result;
    }


}
